<!--  -->
<template>
  <div class="setting-container">
    <el-card>
      <div slot="header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-row>
        <el-col :span="16">
          <el-form ref="user"
                   :model="user"
                   label-width="80px">
            <el-form-item label="编号">
              {{user.id}}
            </el-form-item>
            <el-form-item label="手机">
              {user.mobile}
            </el-form-item>
            <el-form-item label="媒体名称">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍">
              <el-input type="textarea"
                        v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="user.email"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary"
                         @click="onUpdataUser"
                         :loading='updataProfileLoading'>保存</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- offset位置 -->
        <el-col :offset="2"
                :span="4">

          <!-- 第一种方法 -->
          <!-- <p @click="$refs.file.click()">点击修改头像</p>
          <input type="file"
                 hidden
                 ref="file"> -->
          <!-- 第二种方法 -->
          <!-- <label for="file">点击修改头像</label>
          <input id="file"
                 type="file"
                 hidden
                 ref="file"> -->
          <label for="file">
            <el-avatar shape="square"
                       :size="150"
                       fit="cover"
                       :src="user.photo"></el-avatar>
          </label>
          <input id="file"
                 type="file"
                 ref="file"
                 hidden
                 @change="onFileChange">
        </el-col>
      </el-row>
    </el-card>
    <!-- 选择图片提示 -->
    <el-dialog title="修改头像"
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose"
               append-to-body
               @opened="onDialogOpen"
               @closed="onDialogClose">
      <div class="preview-image-wrap">
        <img class="preview-image"
             :src="priviewImage"
             ref="preview-image"
             alt=""
             id="image">
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   :loading="uploadPhotoLoading"
                   @click="onUpdataPhoto">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updataUserPhoto, upadataUserprofile } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import gloobalBus from '@/utils/global-bus'

export default {
  name: 'SettingIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        email: '',
        intro: '',
        id: null,
        name: '',
        mobile: '',
        photo: ''
      },
      dialogVisible: false,
      priviewImage: '',
      cropper: null,
      uploadPhotoLoading: false,
      updataProfileLoading: false
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadUser()
  },
  mounted () { },
  methods: {
    // 修改用户资料
    onUpdataUser () {
      this.updataProfileLoading = true
      const { name, intro, email } = this.user
      upadataUserprofile({
        name,
        intro,
        email
      }).then(res => {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.updataProfileLoading = false
        gloobalBus.$emit('updata-user', this.user)
      })
    },
    loadUser () {
      getUserProfile().then(res => {
        this.user = res.data.data
      })
    },
    onFileChange () {
      // 处理图片预览
      const file = this.$refs.file
      // console.log(file.files[0])
      // 将图片对象设置为图片的src
      const blobData = window.URL.createObjectURL(file.files[0])
      // console.log(blobData)
      this.priviewImage = blobData
      // 展示弹出层，预览用户选择的图片
      this.dialogVisible = true
      // 解决选择相同文件不触发change事件问题
      this.$refs.file.value = ''
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    onDialogOpen () {
      // 获取图片dom
      // 图片裁切器必须基于img进行初始化,注意，img必须是可见状态才能正常运行初始化,
      // 因为我们这里要在对话框里面初始化裁切器，所以务必要在对话框完全打开的状态去进行初始化
      // const image = document.getElementById('image');
      const image = this.$refs['preview-image']
      // 第一次初始化，图片发生变化，裁切器不会更新，
      // 方法一：裁切器.replace方法
      // 方法二：销毁裁切器，重新初始化
      this.cropper = new Cropper(image, {
        aspectRatio: 16 / 9,
        viewMode: 1,
        dragMode: 'none',
        cropBoxResizable: false
        // crop (event) {
        //   console.log(event.detail.x)
        //   console.log(event.detail.y)
        //   console.log(event.detail.width)
        //   console.log(event.detail.height)
        //   console.log(event.detail.rotate)
        //   console.log(event.detail.scaleX)
        //   console.log(event.detail.scaleY)
        // }
      })
    },
    onDialogClose () {
      // 对话框关闭，销毁裁切器,或者用.replace也可以实现
      this.cropper.destroy()
    },
    onUpdataPhoto () {
      this.uploadPhotoLoading = true
      // 获取裁切的图片对象
      this.cropper.getCroppedCanvas().toBlob((file) => {
        const fd = new FormData()
        fd.append('photo', file)
        // 请求更新用户头像
        updataUserPhoto(fd).then(res => {
          this.dialogVisible = false
          this.user.photo = window.URL.createObjectURL(file)

          gloobalBus.$emit('updata-user', this.user)
          // 把服务器端的图片返回展示有点慢
          // this.user.photo = res.data.data.photo
        })
      })
      // 关闭对话框
      this.uploadPhotoLoading = false
      this.$message({
        type: 'success',
        message: '修改成功'
      })

      // 更新视图展示
    }
  }
}
</script>

<style lang='less' scoped>
.preview-image-wrap {
  .preview-image {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
    height: 200px;
  }
}
</style>
